package com.fyfeng.fcanvas;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.util.Log;

public class FFileUtils {

	private static final String tag = FFileUtils.class.getSimpleName();

	public static String mOriginalFile = "page.jpg";
	public static String mNoteFile = "note_page.png";

	private static File getOriginalFile(String filename) {

		File storagedir = Environment.getExternalStorageDirectory();

		File mypics_dir = new File(storagedir, "fyfeng");
		if (!mypics_dir.exists()) {

			mypics_dir.mkdirs();

			return null;
		}

		File mypaint_pic = new File(mypics_dir, filename);

		return mypaint_pic.exists() ? mypaint_pic : null;

	}

	private static File getNoteFile(String filename) {
		File storagedir = Environment.getExternalStorageDirectory();

		File mypics_dir = new File(storagedir, "fyfeng");
		if (!mypics_dir.exists()) {

			mypics_dir.mkdirs();

			return null;
		}

		File mypaint_pic = new File(mypics_dir, filename);

		return mypaint_pic.exists() ? mypaint_pic : null;
	}

	public static Bitmap getOriginalBitmap(String filename) {
		Bitmap bitmap = null;

		File file = FFileUtils.getOriginalFile(FFileUtils.mOriginalFile);

		if (null == file || !file.exists()) {
			return null;
		}

		bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()).copy(Bitmap.Config.ARGB_8888, true);

		return bitmap;
	}

	public static Bitmap getNoteBitmap(String filename) {
		Bitmap bitmap = null;

		File file = FFileUtils.getNoteFile(FFileUtils.mNoteFile);

		if (null == file || !file.exists()) {
			return null;
		}

		bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()).copy(Bitmap.Config.ARGB_8888, true);

		return bitmap;
	}

	public static boolean saveNoteFile(Bitmap bitmap, String filename) {

		File dir = Environment.getExternalStorageDirectory();

		File mypics_dir = new File(dir, "fyfeng");
		if (!mypics_dir.exists()) {
			if (!mypics_dir.mkdirs()) {
				Log.e(tag, "在扩展卡中创建fyfeng目录失败!");
				return false;
			}
		}

		File mypaint_pic = new File(mypics_dir, FFileUtils.mNoteFile);
		FileOutputStream stream = null;
		try {
			stream = new FileOutputStream(mypaint_pic);
			bitmap.compress(CompressFormat.PNG, 100, stream);
			stream.flush();
			Log.i(tag, "图片保存成功. 保存位置:" + mypaint_pic.getAbsolutePath());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(tag, "保存文件出现异常!");
			return false;
		} finally {
			if (null != stream) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
